package com.xidata.dict.client.embedded.service.impl;

import com.xidata.dict.client.embedded.TargetLanguageHolder;
import com.xidata.dict.client.embedded.model.CodeDictItem;
import com.xidata.dict.client.embedded.model.TextDictItem;
import com.xidata.dict.client.embedded.service.CodeDictTranslator;
import com.xidata.dict.client.embedded.service.TextDictTranslator;
import com.xidata.dict.entity.CodeDict;
import com.xidata.dict.model.LookupRequest;
import com.xidata.dict.service.CodeDictService;
import com.xidata.dict.service.CodeMainLanguageService;
import com.xidata.dict.service.TranslateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Optional;

@Component
public class CodeDictTranslatorImpl implements CodeDictTranslator, TextDictTranslator {
    @Resource
    CodeDictService codeDictService;

    @Resource
    CodeMainLanguageService codeMainLanguageService;

    @Resource
    TranslateService translateService;

    public void translate(String codeType, String language, CodeDictItem item) {

        Optional<CodeDict> lookup = codeDictService.lookup(codeType, item.getCode(), language);
        lookup.ifPresent(codeDict -> {
            item.setCodeName(codeDict.getText());
        });
    }

    @Override
    public void translate(String codeType, CodeDictItem item) {
        String targetLanguage = TargetLanguageHolder.get();
        if (needTranslate()) {
            translate(codeType, targetLanguage, item);
        }
    }

    private boolean needTranslate() {
        String targetLanguage = TargetLanguageHolder.get();
        return StringUtils.isNotEmpty(targetLanguage) && !codeMainLanguageService.getMainLanguage().equals(targetLanguage);
    }

    @Override
    public void translate(TextDictItem item) {
        if (needTranslate()) {

            LookupRequest request = new LookupRequest();
            request.setSourceLanguage(codeMainLanguageService.getMainLanguage());
            request.setTargetLanguage(TargetLanguageHolder.get());
            request.setText(item.getText());
            String translate = translateService.translate(request);
            item.setText(translate);
        }

    }
}
